<template>
  <!--  面包屑-->
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>报修服务</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card style="margin-bottom: 20px;">
    <div class="row-play" >
      <el-radio-group v-model="searchForm.status" @change="getPage">
        <el-radio-button :label=null value=null class="item">全部维修单</el-radio-button>
        <el-badge :value="numForm.pendingNum" :max="99" class="item" :hidden="numForm.pendingNum===0">
          <el-radio-button :label="2" value="2">待接单</el-radio-button>
        </el-badge>
        <el-badge :value="numForm.notContactNum" :hidden="numForm.notContactNum===0" :max="99" class="item">
          <el-radio-button :label="3" value="3">联系维修人员</el-radio-button>
        </el-badge>
        <el-badge :value="numForm.repairingNum" :hidden="numForm.repairingNum===0" :max="99" class="item">
          <el-radio-button :label="4" value="4">正在维修</el-radio-button>
        </el-badge>
        <el-radio-button :label="5" value="5" class="item">已完成</el-radio-button>
        <el-radio-button :label="6" value="6">已取消</el-radio-button>
      </el-radio-group>
      <el-button style="margin-left: 300px;" type="info" @click="add">新增故障单</el-button>
    </div>
    </el-card>
    <div class="row-play">
      单号：
      <el-input size="small" class="row-play-play" v-model="searchForm.repairNum" placeholder="请输入内容"></el-input>
      手机号：
      <el-input size="small" class="row-play-play" v-model="searchForm.phone" placeholder="请输入内容"></el-input>
      姓名：
      <el-input size="small" class="row-play-play" v-model="searchForm.name" placeholder="请输入内容"></el-input>
      <el-date-picker
          size="small"
          style="width: 220px"
          v-model="searchForm.timeValue"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
          class="row-play-p"
          value-format="yyyy-MM-dd HH:mm:ss"
      >
      </el-date-picker>
      <el-button class="row-play-p" @click="getPage" size="small">搜索</el-button>
      <el-button class="row-play-p" @click="toggleSelection()" size="small">取消选择</el-button>
      <el-button @click="deleteMany" v-show="searchForm.status>4" size="small" type="danger">批量删除</el-button>
    </div>
    <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange">
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column
          label="修改时间"
          width="180">
        <template slot-scope="scope">{{ scope.row.updateTime }}</template>
      </el-table-column>
      <el-table-column
          label="订单号"
          width="180">
        <template slot-scope="scope">
          {{ scope.row.repairNum }}
        </template>
      </el-table-column>
      <el-table-column
          label="用户名"
          width="220">
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="top">
            <p>用户地址：{{ scope.row.region }} </p>
            <p>详细地址：{{ scope.row.location }}</p>
            <p>手机号：{{ scope.row.phone }}</p>
            <p>创建时间: {{ scope.row.createTime }}</p>
            <p>修改人: {{ scope.row.updateUserName }}</p>
            <p>修改时间: {{ scope.row.updateTime }}</p>
            <div slot="reference" class="name-wrapper">
              <el-tag size="medium">{{ scope.row.name }}</el-tag>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column
          label="图片"
          width="120">
        <template slot-scope="scope">
          <el-image
              style="width: 50px; height: 50px"
              :src="scope.row.image"
              :preview-src-list=[scope.row.image]>
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <div class="row-play">
            <el-popover trigger="hover" placement="top">
              <p style="max-width: 200px">{{ scope.row.detail }}</p>
              <div slot="reference" class="name-wrapper">
                <el-tag class="row-play-p" size="medium">故障详情</el-tag>
              </div>
            </el-popover>
            <el-popover trigger="hover" placement="top" v-show="scope.row.status===6">
              <p style="max-width: 200px">{{ scope.row.cancelReason }}</p>
              <div slot="reference" class="name-wrapper">
                <el-tag class="row-play-p" size="medium">取消原因</el-tag>
              </div>
            </el-popover>
            <el-button
                size="mini"
                v-show="scope.row.status<5"
                @click="addStatus(scope.row)"
                type="success">下一步
            </el-button>
            <el-button
                size="mini"
                v-show="scope.row.status<5"
                @click="cancelStatus(scope.row)">取消
            </el-button>
            <el-button
                size="mini"
                type="danger"
                v-show="scope.row.status>4"
                @click="handleDelete(scope.row)">删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 40]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalSize">
      </el-pagination>
    </div>
    <el-dialog title="新增故障报单" :visible.sync="dialogAddFormVisible">
      <el-form ref="formRef" :model="addForm" :rules="formRules">
        <el-form-item label="分类名称" :label-width="formLabelWidth">
          <el-autocomplete
              v-model="addForm.categoryName"
              :fetch-suggestions="querySearchAsyncCategoryName"
              placeholder="请输入内容"
              size="mini"
              style="width: 300px;margin-right: 10px;"
              :maxlength=maxlength
              :minlength=minlength
              show-word-limit
          ></el-autocomplete>
        </el-form-item>
        <el-form-item label="设备名称" :label-width="formLabelWidth" >
          <el-autocomplete
              v-model="addForm.deviceName"
              :fetch-suggestions="querySearchAsyncDeviceName"
              placeholder="请输入内容"
              size="mini"
              style="width: 300px;margin-right: 10px;"
              :maxlength=maxlength
              :minlength=minlength
              show-word-limit
          ></el-autocomplete>
        </el-form-item>
        <el-form-item label="版本号" :label-width="formLabelWidth" style="width: 400px">
          <el-autocomplete
              v-model="addForm.deviceVersion"
              :fetch-suggestions="querySearchAsyncDeviceVersion"
              placeholder="请输入版本号：x.x.x"
              size="mini"
              style="width: 300px;margin-right: 10px;"
              :maxlength=maxlength
              :minlength=minlength
              show-word-limit
          ></el-autocomplete>
        </el-form-item>
        <el-form-item label="功能名称" :label-width="formLabelWidth" style="width: 400px">
          <el-autocomplete
              v-model="addForm.functionName"
              :fetch-suggestions="querySearchAsyncFunctionName"
              placeholder="请输入内容"
              size="mini"
              style="width: 300px;margin-right: 10px;"
              :maxlength="15"
              show-word-limit
          ></el-autocomplete>
        </el-form-item>
        <el-form-item label="用户名" :label-width="formLabelWidth"  prop="name">
          <el-input v-model="addForm.name" placeholder="请输入内容" size="mini" style="width: 300px"></el-input>
        </el-form-item>
        <el-form-item label="手机号" :label-width="formLabelWidth" prop="phone">
          <el-input v-model="addForm.phone" placeholder="请输入内容" size="mini" style="width: 300px"></el-input>
        </el-form-item>
        <el-form-item label="地址" :label-width="formLabelWidth" prop="region">
          <el-cascader v-model="region" placeholder="请输入内容"
                       :options="options"
                       style="width: 400px"
                       size="mini"
                       @change="handleChange">
          </el-cascader>
        </el-form-item>
        <el-form-item label="详细地址" :label-width="formLabelWidth"  prop="location">
          <el-input v-model="addForm.location" placeholder="请输入内容" size="mini" style="width: 400px"></el-input>
        </el-form-item>
        <el-form-item label="故障详情" :label-width="formLabelWidth" >
          <el-input
              type="textarea"
              placeholder="请输入内容"
              style="width: 400px"
              v-model="addForm.detail"
              maxlength="100"
              show-word-limit
              size="mini"
          ></el-input>
        </el-form-item>
        <el-form-item label="上传图片" :label-width="formLabelWidth" >
          <el-upload
              class="avatar-uploader"
              style="width: 180px"
              :action="uploadUrl"
              :headers="customHeaders"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :on-success="successUpload"
          >
            <img v-if="addForm.image" :src="addForm.image" class="avatar" alt="图片错误">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogAddFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRepair">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {regionData} from 'element-china-area-data'

export default {
  data() {
    return {
      region: null,
      options: regionData,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },

      formRules: {
        phone: [{required: true, message: '请输入手机号', trigger: 'blur'},
          {min: 11, max: 11, message: '长度为11位', trigger: 'blur'}],
        region: [{required: true, message: '请输入地址', trigger: 'blur'}],
        location: [{required: true, message: '请输入详细地址', trigger: 'blur'},
          {min: 1, max: 11, message: '长度为1到15个字符', trigger: 'blur'}],
        name: [{required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 1, max: 11, message: '长度为1到15个字符', trigger: 'blur'}]
      },
      customHeaders: {
        Token: window.sessionStorage.getItem('token')
      },
      uploadUrl: 'http://localhost:8081/aliOss/upload',
      dialogAddFormVisible: false,
      maxlength: 15,
      minlength: 1,
      searchForm: {
        name: '',
        repairNum: '',
        phone: '',
        status: null,
        timeValue: []
      },
      addForm: {
        name: '',
        functionName: '',
        deviceVersion: '',
        deviceName: '',
        status: 2,
        categoryName: '',
        phone: '',
        region: '',
        location: '',
        detail: '',
        image: ''
      },
      statusValue: null,
      tableData: [],
      multipleSelection: [],
      currentPage: 1,
      pageSize: 10,
      totalSize: 0,
      dialogFormVisible: false,
      formLabelWidth: '120px',
      numForm: {
        pendingNum: 0,
        notContactNum: 0,
        repairingNum: 0,

      }
    };
  },
  methods: {
    async addStatus(row){
      const {data: res} = await this.$http.put("/repair/addStatus",{
        id:row.id,
        status:row.status
      });
      if(res.code===0){
        this.$message.error(res.msg);
      }
      this.$message.success("修改成功");
      await this.getPage();
    },
    handleChange(value) {
      let cityLabel = '';
      this.options.forEach(province => {
        if (province.value === value[0]) {
          this.addForm.region += province.label;
          if (province.children) {
            province.children.forEach(city => {
              if (city.value === value[1]) {
                this.addForm.region += '/' + city.label;
                if (city.children) {
                  city.children.forEach(area => {
                    if (area.value === value[2]) {
                      this.addForm.region += '/' + area.label;
                      return;
                    }
                  });
                }
              }
            });
          }
        }
      });
      this.addForm.region += '/' + cityLabel;
      console.log(this.addForm.region)
    },
    beforeAvatarUpload(file) {
      let index = file.name.lastIndexOf(".");
      let extension = file.name.substr(index + 1);
      let extensionList = [
        "png",
        "PNG",
        "jpg",
        "JPG",
        "jpeg",
        "JPEG",
        "bmp",
        "BMP",
      ];
      if (extensionList.indexOf(extension) < 0) {
        this.$message({
          message: "当前文件格式不支持",
          type: "error",
          center: true,
        });

        return false;
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
        return false;
      }
    },
    successUpload(response) {
      this.addForm.image = response.data;
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该报单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(async () => {
        const {data: res} = await this.$http.delete("/repair/" + row.id);
        if (res.code === 0) {
          return this.$message.error(res.msg);
        }
        await this.getPage();
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getPage();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getPage();
    },
    async getPage() {
      const {data: res} = await this.$http.get("/repair/page", {
        params: {
          page: this.currentPage,
          pageSize: this.pageSize,
          status: this.searchForm.status,
          name: this.searchForm.name,
          phone: this.searchForm.phone,
          repairNum: this.searchForm.repairNum,
          startTime: this.searchForm.timeValue&&this.searchForm.timeValue[0]?this.searchForm.timeValue[0].toString():null,
          endTime: this.searchForm.timeValue&&this.searchForm.timeValue[1]?this.searchForm.timeValue[1].toString():null
        }
      });
      if (res.code === 0) {
        return this.$message.error("获取报单信息失败");
      }
      this.tableData = res.data.records;
      this.totalSize = res.data.total;
      await this.getNumWithNull();
      await this.getCategoryNameList();
      await this.getDeviceNameVersionList();
      await this.getFunctionNameList();
    },
    async getNumWithNull() {
      const {data: res} = await this.$http.get("/repair/num");
      if (res.code === 0) {
        return this.$message.error("获取报单数失败");
      }
      this.numForm=res.data;
    },
    deleteMany() {
      let ids = [];
      this.multipleSelection.forEach(row => {
        ids.push(row.id);
      })
      let idss = ids.join(',');
      this.$confirm('此操作将永久删除多个报单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(async () => {
        const {data: res} = await this.$http.delete("/repair", {
          params: {
            ids: idss
          }
        });
        if (res.code === 0) {
          return this.$message.error(res.msg);
        }
        await this.getPage();
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    add() {
      this.dialogAddFormVisible = true;
    },
    addRepair() {
      this.$refs.formRef.validate(async valid => {
        if (!valid) return false;
        this.dialogAddFormVisible = false;
        const {data: res} = await this.$http.post("/repair/add", this.addForm);
        if (res.code === 0) {
          return this.$message.error(res.msg);
        }
        this.$message.success("添加成功");
        await this.getPage();
      })
    },
    cancelStatus(row) {
      this.$prompt('请输入原因', '取消原因', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^.{1,15}$/,
        inputErrorMessage: '字符长度必须在1到15之间',
        inputValue: row.cancelReason
      }).then(async ({value}) => {
        const {data: res} = await this.$http.put("/repair/cancelStatus",{
          id:row.id,
          cancelReason:value
        });
        if(res.code===0){
          this.$message.error(res.msg);
        }
        this.$message.success("修改成功");
        await this.getPage();
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        });
      });
    },
    querySearchAsyncCategoryName(queryString, callback) {
      var categoryNameList = this.categoryNameList;
      var results = queryString ? categoryNameList.filter(this.createStateFilter(queryString)) : categoryNameList;
      callback(results);
    },
    querySearchAsyncDeviceName(queryString, callback) {
      var deviceNameList = this.deviceNameList;
      var results = queryString ? deviceNameList.filter(this.createStateFilter(queryString)) : deviceNameList;
      callback(results);
    },
    querySearchAsyncDeviceVersion(queryString, callback) {
      var deviceVersionList = this.deviceVersionList;
      var results = queryString ? deviceVersionList.filter(this.createStateFilter(queryString)) : deviceVersionList;
      callback(results);
    },
    querySearchAsyncFunctionName(queryString, callback) {
      var functionNameList = this.functionNameList;
      var results = queryString ? functionNameList.filter(this.createStateFilter(queryString)) : functionNameList;
      callback(results);
    },
    createStateFilter(queryString) {
      return (state) => {
        return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    async getCategoryNameList() {
      const {data: res} = await this.$http.get("/category/nameList");
      if (res.code === 0) {
        return this.$message.error(res.msg);
      }
      this.categoryNameList = res.data;
    },
    async getDeviceNameVersionList() {
      const {data: res} = await this.$http.get("/device/nameVersionList");
      if (res.code === 0) {
        return this.$message.error("获取设备名和设备版本失败");
      }
      if (res.data !== null) {
        this.deviceNameList = res.data.nameSet;
        this.deviceVersionList = res.data.versionSet;
      }
    },
    async getFunctionNameList() {
      const {data: res} = await this.$http.get("/function/nameList");
      if (res.code === 0) {
        return this.$message.error("获取功能名称失败");
      }
      if (res.data !== null) {
        this.functionNameList = res.data;
      }
    },
    initWebSocket() {
      // 创建 WebSocket 对象
      this.websocket = new WebSocket('ws://127.0.0.1:8081/im/server/1');

      // 监听 WebSocket 连接成功事件
      this.websocket.onopen = () => {
        console.log('WebSocket 连接成功');
      };

      // 监听 WebSocket 接收消息事件
      this.websocket.onmessage = (event) => {
        const message = event.data;
        console.log('收到服务器消息:', message);

        // 解析消息并进行处理
        const parsedMessage = JSON.parse(message);
        const msg=parsedMessage.msg;
        this.$notify({
          title: '请及时处理',
          message: msg,
          type: 'warning',
          duration: 0
        });
        // const temper = parsedMessage.notify_data.body.services[0].properties.temper;
        // const humidness = parsedMessage.notify_data.body.services[0].properties.humidness;
        // console.log(temper);
        // 将 temper 值添加到 tableData 数组中
        // this.tableData.push({ temper, humidness, value: '其他数值' });
      };

      // 监听 WebSocket 连接关闭事件
      this.websocket.onclose = () => {
        console.log('WebSocket 连接关闭');
      };

      // 监听 WebSocket 错误事件
      this.websocket.onerror = (error) => {
        console.error('WebSocket 错误:', error);
      };
    }
  },
  mounted() {
    this.getPage();
    this.initWebSocket();
  }
}
</script>

<style scoped lang="less">
.item {
  margin-right: 40px;
}

/deep/ .el-radio-button:first-child .el-radio-button__inner {
  border-radius: 1px
}

/deep/ .el-radio-button:last-child .el-radio-button__inner{
  border-radius: 1px;
}
.row-play {
  display: flex;
  align-items: center;

  .row-play-play {
    width: 200px;
    margin-right: 10px;
  }

  .row-play-p {
    margin-right: 10px;
  }
}

.block {
  text-align: center;
}

/deep/ .el-radio-button__inner {
  background-color: #dddddd;
}


.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;

  :hover {
    border-color: #409EFF;
  }
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>